import { FlatList, ListRenderItem, PixelRatio, Pressable, RefreshControl, Text, View } from 'react-native'
import { NavigationProps, withNavigationItem } from 'hybrid-navigation'
import { AppPage } from '../AppPage'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'

export default withNavigationItem({ titleItem: { title: '首页' } })(HomePage)

function HomePage({ navigator }: NavigationProps) {
  useEffect(() => {
    for (let a in AppPage) {
      console.log(a)
    }
  })
  const DATA = useMemo<AppPage[]>(() => {
    const pages: AppPage[] = []
    for (let appPageKey in AppPage) {
      if (appPageKey !== AppPage.HomePage) {
        pages.push(appPageKey as AppPage)
      }
    }
    return pages
  }, [])

  const renderItemSeparator = useCallback(
    // () => <View style={{ backgroundColor: '#000000', height: StyleSheet.hairlineWidth * 2 }}></View>,
    () => <View style={{ backgroundColor: '#000000', height: PixelRatio.roundToNearestPixel(1) }}></View>,
    [],
  )

  const onPress = useCallback(
    (appPage: AppPage) => {
      console.log(appPage)
      navigator.push(appPage)
    },
    [navigator],
  )

  const renderItem: ListRenderItem<AppPage> = useCallback(
    ({ item }) => (
      <Pressable
        onPress={() => onPress(item)}
        style={{
          flex: 1,
          flexDirection: 'row',
          backgroundColor: '#FF0000',
          height: 50,
          alignItems: 'center',
          paddingHorizontal: 12,
        }}>
        <Text style={{ fontSize: 16 }}>{item}</Text>
      </Pressable>
    ),
    [onPress],
  )

  const [refreshing, setRefreshing] = useState(false)
  const onRefresh = useCallback(() => {
    setRefreshing(true)
    setTimeout(() => setRefreshing(false), 2000)
  }, [])

  return (
    <View style={{ flex: 1 }}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={item => item}
        refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}
        ItemSeparatorComponent={renderItemSeparator}
      />
    </View>
  )
}
